<template>
  <div class="container">
    <div id="map" class="map__x"></div>
    <hkVideo
      class="hkVideo"
      ref="hkVideoRef"
      v-if="hkVideoShow"
      @close="hkVideoShow = false"
      :appkey="config.appkey"
      :ip="config.ip"
      :secret="config.secret"
      :cameraIndexCode="config.cameraIndexCode"
      :port="config.port"
    ></hkVideo>
    <el-button @click="openDrawer" class="configBtn">配置</el-button>
    <el-button @click="closeHkVideo" v-show="hkVideoShow" class="closeBtn"
      >关闭监控</el-button
    >
    <el-drawer
      v-model="configDrawerShow"
      title="配置"
      direction="rtl"
      :close-on-click-modal="false"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <el-form-item label="平台提供的 APPKey">
            <el-input v-model="form.appkey" autocomplete="off" />
          </el-form-item>
          <el-form-item label="平台提供的 APPSecret">
            <el-input v-model="form.secret" autocomplete="off" />
          </el-form-item>
          <el-form-item label="平台IP 地址">
            <el-input v-model="form.ip" autocomplete="off" />
          </el-form-item>
          <el-form-item label="平台端口">
            <el-input v-model="form.port" autocomplete="off" />
          </el-form-item>
          <el-form-item label="监控点编号">
            <el-input v-model="form.cameraIndexCode" autocomplete="off" />
          </el-form-item>
          <el-divider />
          <el-form-item label="地图">
            <el-input v-model="form.mapUrl" autocomplete="off" />
          </el-form-item>
          <el-form-item label="坐标系">
            <el-input v-model="form.projection" autocomplete="off" />
          </el-form-item>
          <el-form-item label="点的经度">
            <el-input v-model="form.lng" autocomplete="off" />
          </el-form-item>
          <el-form-item label="点的纬度">
            <el-input v-model="form.lat" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button type="primary" @click="onSave"> 保存 </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue"; // vue相关方法
import { Vector as VectorLayer, Tile as TileLayer } from "ol/layer";
import Feature from "ol/Feature";
import { TileSuperMapRest } from "@supermap/iclient-ol";
import VectorSource from "ol/source/Vector";
import Point from "ol/geom/Point";
import { Style, Circle, Fill, Icon, Stroke } from "ol/style";
import { Map, View, Overlay } from "ol";
import "ol/ol.css"; // 地图样式
import hkVideo from "@/components/hkVideo/index.vue";
import request from "@/api/request.ts";
import { md5 } from "js-md5";
import { Base64 } from "js-base64";
import axios from "axios";

onMounted(() => {
  initMap();
});

const hkVideoRef = ref();
let map: Map;
let tLayer: TileLayer<any>;
let vLayer: VectorLayer<any>;
let pointGeometry: Point;
const hkVideoShow = ref(false);
const configDrawerShow = ref(false);
const config = reactive({
  appkey: "27576186",
  ip: "116.63.194.174",
  secret: "vhjcqyJV4n8jaVPu6pKf",
  cameraIndexCode: "e5d6bf643a624532850899b4fb69f3ac",
  port: 443,
});

function strToUtf8Bytes(str) {
  const utf8 = [];
  for (let ii = 0; ii < str.length; ii++) {
    let charCode = str.charCodeAt(ii);
    if (charCode < 0x80) utf8.push(charCode);
    else if (charCode < 0x800) {
      utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
    } else if (charCode < 0xd800 || charCode >= 0xe000) {
      utf8.push(
        0xe0 | (charCode >> 12),
        0x80 | ((charCode >> 6) & 0x3f),
        0x80 | (charCode & 0x3f)
      );
    } else {
      ii++;
      // Surrogate pair:
      // UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
      // splitting the 20 bits of 0x0-0xFFFFF into two halves
      charCode =
        0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
      utf8.push(
        0xf0 | (charCode >> 18),
        0x80 | ((charCode >> 12) & 0x3f),
        0x80 | ((charCode >> 6) & 0x3f),
        0x80 | (charCode & 0x3f)
      );
    }
  }
  //兼容汉字，ASCII码表最大的值为127，大于127的值为特殊字符
  for (let jj = 0; jj < utf8.length; jj++) {
    var code = utf8[jj];
    if (code > 127) {
      utf8[jj] = code - 256;
    }
  }
  return utf8;
}

function getXCaSignature({
  method = "POST",
  accept = "application/json, text/plain, */*",
  bodyStream = {},
  contentType = "text/plain;charset=UTF-8",
  date = new Date(),
  headers = {},
  url = ""
}) {
  const contentMD5 = Base64.encode(
    md5(strToUtf8Bytes(JSON.stringify(bodyStream)))
  );
  let str = method + "\n" + accept + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n"
  console.log(headers,'headers')
  for(let key in headers){
    str += (key + ':' + headers[key] + "\n")
  }
  str += url
  return str
}

const headers = {
  "X-Ca-Key": config.appkey,
  "X-Ca-Signature": "",
  "X-Ca-Signature-Headers": "",
  "X-Ca-Timestamp": new Date().getTime(),
  "X-Ca-Nonce": getUUId()
};

console.log(getXCaSignature({
  headers,
  bodyStream: {
    pageNo: 0,
    pageSize: 10
  },
  url: "https://116.63.194.174:443/api/resource/v1/cameras"
}))

console.log(headers, "headers");

function getUUId(tem = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") {
  let id = "",
    len = tem.length,
    i = 0;
  for (i; i < len; i++) {
    if (tem[i] == "-") id += tem[i];
    else {
      let num = Math.floor(Math.random() * 16);
      id += num.toString(16);
    }
  }
  return id;
}

// request
//   .post(
//     "/api/v1/oauth/token",
//     {},
//     {
//       headers,
//     }
//   )
//   .then((res) => {
//     console.log(res);
//   })
//   .catch((err) => {
//     console.error(err);
//   });

// request.post("/api/resource/v1/cameras", {
//   pageNo: 0,
//   pageSize: 10
// }).then(res => {
//   console.log(res)
// }).catch(err => {
//   console.error(err)
// })

const mapConfig = reactive({
  url: "https://iserver.supermap.io/iserver/services/map-world/rest/maps/World",
  //   url: 'https://iserver.supermap.io/iserver/services/map-china400/rest/maps/China',
  projection: "EPSG:4326",
  lng: 114.064839,
  lat: 22.548857,
});
const form = reactive({
  appkey: "",
  ip: "",
  secret: "",
  cameraIndexCode: "",
  port: 443,
  mapUrl: "",
  projection: "",
  lng: 0,
  lat: 0,
});

function closeHkVideo() {
  if (hkVideoRef.value) {
    hkVideoRef.value.close();
  }
}

function openDrawer() {
  configDrawerShow.value = true;
  form.appkey = config.appkey;
  form.ip = config.ip;
  form.secret = config.secret;
  form.cameraIndexCode = config.cameraIndexCode;
  form.port = config.port;
  form.mapUrl = mapConfig.url;
  form.projection = mapConfig.projection;
  form.lng = mapConfig.lng;
  form.lat = mapConfig.lat;
}

function onSave() {
  config.appkey = form.appkey;
  config.ip = form.ip;
  config.secret = form.secret;
  config.cameraIndexCode = form.cameraIndexCode;
  config.port = form.port;
  configDrawerShow.value = false;
  if (form.mapUrl != mapConfig.url || form.projection != mapConfig.projection) {
    mapConfig.url = form.mapUrl;
    mapConfig.projection = form.projection;
    if (tLayer) {
      tLayer.setSource(createSource());
    }
  }
  if (form.lng != mapConfig.lng || form.lat != mapConfig.lat) {
    mapConfig.lng = form.lng;
    mapConfig.lat = form.lat;
    if (pointGeometry) {
      pointGeometry.setCoordinates([mapConfig.lng, mapConfig.lat]);
    }
  }
}

function createSource() {
  return new TileSuperMapRest({
    url: mapConfig.url,
    // prjCoordSys: 'EPSG:3875'
    projection: mapConfig.projection,
  });
}

function initMap() {
  map = new Map({
    target: "map", // 绑定html元素
    view: new View({
      // 地图视图
      projection: "EPSG:4326", // 坐标系，有EPSG:4326和EPSG:3857
      center: [mapConfig.lng, mapConfig.lat], // 深圳坐标
      zoom: 12, // 地图缩放级别（打开页面时默认级别）
    }),
  });

  tLayer = new TileLayer({
    source: createSource(),
  });

  map.addLayer(tLayer);

  pointGeometry = new Point([mapConfig.lng, mapConfig.lat]);

  vLayer = new VectorLayer({
    source: new VectorSource({
      features: [
        new Feature({
          geometry: pointGeometry,
          name: "视频点",
        }),
      ],
    }),
    style: new Style({
      image: new Circle({
        radius: 20,
        fill: new Fill({
          color: "red",
        }),
      }),
    }),
  });

  map.addLayer(vLayer);

  //   var popup = new Overlay({
  //     element: document.getElementById("playWnd"),
  //     autoPan: true,
  //     positioning: "bottom-center",
  //     stopEvent: true,
  //     autoPanAnimation: {
  //       duration: 250,
  //     },
  //   });

  //   map.addOverlay(popup);

  map.on("click", function (e) {
    // var coordinate = e.coordinate;
    var feature = map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
      return feature;
    });
    if (feature) {
      hkVideoShow.value = true;
      //   popup.setPosition(coordinate);
    }
  });
}

// function positionIcon(center) {
//     var iconFeature = new Feature({
//         geometry: new Point(center),
//         name: '当前位置',
//         population: 4000,
//         rainfall: 500
//     })
//     var iconStyle = new Style({
//         image: new Icon({
//             anchor: [0.5, 46],
//             scale: 0.4,
//             anchorXUnits: 'fraction',
//             anchorYUnits: 'pixels',
//             src: '/static/images/dingwei.png'
//         })
//     })
//     iconFeature.setStyle(iconStyle)
//     const positionLayer = new VectorLayer({
//         source: new VectorSource({
//             features: [iconFeature]
//         })
//     })

//     map.addLayer(positionLayer)
// }
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100%;
  height: 100%;
}
.configBtn {
  position: absolute;
  top: 10px;
  right: 10px;
}
.closeBtn {
  position: absolute;
  top: 10px;
  right: 100px;
}
</style>